import { message_send } from '@/apis';
import { Button, ProgressCircle, Toast } from 'antd-mobile';
import * as React from 'react';
import { BaseInfo, ChatMessageType } from '../../../serve/interfaces';
import { do_upload, download } from '../../apis/upload'

type FileUploadType = ChatMessageType.FILE | ChatMessageType.IMG | ChatMessageType.VIDEO
export interface UploadProps {
  accept?: 'image/*' | 'video/*' | '*'
  className?: string;
  style?: React.CSSProperties;
  onSuccess?: (url: string) => void;
  children?: React.ReactNode | React.ReactNode[];
}

export const uploadFile = (file: File) => {
  let type: FileUploadType = ChatMessageType.FILE
  let show = '文件'
  if (/image\//.test(file.type)) {
    type = ChatMessageType.IMG
    show = '图片'
  }
  if (/video\//.test(file.type)) {
    type = ChatMessageType.VIDEO
    show = '视频'
  }

  Toast.show({
    icon: 'loading',
    content: `${show}上传中...`,
    duration: 0,
  })

  return new Promise<[FileUploadType, string]>(function (resolve, reject) {
    do_upload(file, {
      onerror: function (err) {
        Toast.clear()
        Toast.show({
          icon: 'fail',
          content: err,
        })
        resolve(null)
      },
      onsuccess: function (id) {
        Toast.clear()
        resolve([type, download(id, file.name)])
      }
    })
  })
}

const Upload = (props: UploadProps) => {
  const { accept = '*', className, style, children, onSuccess } = props
  const [ loading, setLoading ] = React.useState(false)
  const [ percent, setPercent ] = React.useState(0)

  React.useEffect(function () {
    if (!loading) {
      setPercent(0)
    }
  }, [loading])
  const onChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
    const file = e.target.files[0]
    if (file) {
      setLoading(true)
      do_upload(file, {
        onerror: function (err) {
          e.target.value = ''
          setLoading(false)
          Toast.show({
            icon: 'fail',
            content: err,
          })
        },
        onsuccess: function (id) {
          setLoading(false)
          e.target.value = ''
          onSuccess?.(download(id, file.name))
        },
        onprogress: function (loaded, total, xhr) {
          // xhr.abort()
          setPercent(Math.floor(loaded * 100 / total))
        }
      })
    }

  }
  return <label className={className} style={style}>
    {loading ? <Button color="default" shape="rounded">
      <ProgressCircle percent={percent}>
        <small>{percent}%</small>
      </ProgressCircle>
    </Button> : children}
    <input type="file" style={{ display: 'none' }} accept={accept} onChange={onChange}/>
  </label>
}

export default Upload
